//
//  DDLoginViewController.m
//  PrivateCloud
//
//  Created by sarah doo on 13-10-13.
//  Copyright (c) 2013年 sarah doo. All rights reserved.
//

#import "DDLoginViewController.h"
#import "DDLoginSuccessCell.h"
#import "DDLoginSuccessModel.h"
#import "UIColor+.h"
#import "DDAppDelegate.h"
#import "DDVerifyThread.h"
#import "DDTCPListenThread.h"
#import "DDSuccessViewController.h"
#import "MBProgressHUD.h"
#import "DDNetworkUtils.h"
#import "DDSearchAll.h"
#import "NSData+IP.h"
#import "DDSearchAllACK.h"
#import "DDCommentDic.h"
#include <arpa/inet.h>
#include <netdb.h>
#include <net/if.h>
#include <ifaddrs.h>

#define IP_TAG 10000
#define PWD_TAG 10001
#define CONNECT_BTN_TAG 10002
#define SETTING_TAG 10003
#define OK_BUTTON_TAG 10004
#define REMEBER_TAG 10005


@interface DDLoginViewController ()

@end

@implementation DDLoginViewController
@synthesize udpSocket = _udpSocket;

@synthesize isSuccess, searchResults,cloudInfos,curPos,curPwd,isSearch,imageView1,hasSearchResult;

//建立基于UDP的Socket连接
-(void)openUDPServer{
    searchLabel.text = @"搜索开始";
    if (isSearch == YES) {
        return;
    }
    isSearch = NO;
    //开始闪烁
    [self blink];
    if (cloudInfos == nil) {
        cloudInfos = [[NSMutableArray alloc]init];
        self.searchResults = [[NSMutableArray alloc]init];
    }
	//初始化udp
	GCDAsyncUdpSocket *tempSocket=[[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
    

	self.udpSocket=tempSocket;
	[tempSocket release];
	//绑定端口
	NSError *error = nil;
	[self.udpSocket bindToPort:UDP_RECV_PORT error:&error];
    
    //发送广播设置
    [self.udpSocket enableBroadcast:YES error:&error];
    
    //加入群里，能接收到群里其他客户端的消息
    [self.udpSocket joinMulticastGroup:@"224.3.1.1" error:&error];
    
   	//启动接收线程
    //    [self.udpSocket receiveWithTimeout:-1 tag:0];
    if (![self.udpSocket beginReceiving:&error])
    {
        NSLog(@"Error receiving: %@", error);
        return;
    }
    
    
    DDSearchAll* searchAll = [[DDSearchAll alloc]init];
    
    [self.udpSocket sendData:[searchAll entity] toHost:@"224.3.1.1" port:UDP_BROADCAST_PORT withTimeout:-1 tag:CloudCmd_SearchAll];
    //        [self.udpSocket receiveOnce:&error];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        //self.navigationController.navigationBarHidden = YES;
        // Custom initialization
        
    }
    return self;
}

- (void)createStaticViews {
    UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, 30)];
    topView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:topView];
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.frame.size.width/2 - 130, 3, 20, 20)];
    [imageView setImage:[UIImage imageNamed:@"button_internet.png"]];
    [topView addSubview:imageView];
    [imageView release];
    
    
    
    
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.view.frame.size.width/2 - 50, 0, 100, 30)];
    titleLabel.text = @"无 忧 易 云";
    titleLabel.font = [UIFont systemFontOfSize:15];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.backgroundColor = [UIColor clearColor];
    [topView addSubview:titleLabel];
    [titleLabel release];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(self.view.frame.size.width/2 + 50, 0, 30, 30);
//    [button setTitle:@"设  置" forState:UIControlStateNormal];
 //   [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
//    [button addTarget:self action:@selector(setButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
//    UILabel *buttonLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, button.frame.size.width, button.frame.size.height)];
//    buttonLabel.textColor = [UIColor whiteColor];
//    buttonLabel.font = [UIFont systemFontOfSize:15];
//    buttonLabel.backgroundColor = [UIColor redColor];
//    buttonLabel.text = @"设置";
//    [button addSubview:buttonLabel];
//    [buttonLabel release];
//    [topView addSubview:button];
//    [topView release];
    
    UIView *topHalfView = [[UIView alloc] initWithFrame:CGRectMake(0, 50, self.view.frame.size.width, 250)];
    topHalfView.backgroundColor = [UIColor colorWithString:@"#275725"];
    //  topHalfView.backgroundColor = [UIColor colorWithRed:50.0f green:105.0f blue:49.0f alpha:1.0f];
    [self.view addSubview:topHalfView];
    
    
    
    
    UIImage *image = [UIImage imageNamed:@"search.png"];
    imageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 2 -40, 40, image.size.width/2, image.size.height/2)];
    [imageView1 setImage:image];
    [topHalfView addSubview:imageView1];
    imageView1.userInteractionEnabled = YES;
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(searchImagePressed:)];
    [imageView1 addGestureRecognizer:singleTap];
    [singleTap release];
    [imageView1 release];
    
    searchLabel  = [[UILabel alloc] initWithFrame:CGRectMake(imageView1.frame.origin.x , 100, 200, 80)];
    searchLabel.textColor = [UIColor whiteColor];
    searchLabel.font = [UIFont systemFontOfSize:15];
    searchLabel.backgroundColor = [UIColor clearColor];
    searchLabel.text = @"搜索开始";
    [topHalfView addSubview:searchLabel];
    
}

#pragma mark - tableView
//MARS 搜索成功后，显示列表
- (void)createTableView {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 250, self.view.frame.size.width, self.view.frame.size.height - 250)];
    view.backgroundColor = [UIColor colorWithString:@"#273826"];
    [self.view addSubview:view];
    
    
    table = [[UITableView alloc] initWithFrame:CGRectMake(20, 0, self.view.frame.size.width - 40, view.frame.size.height) style:UITableViewStylePlain];
    table.delegate = self;
    table.dataSource = self;
    table.backgroundColor = [UIColor clearColor];
    table.showsHorizontalScrollIndicator = NO;
    table.showsVerticalScrollIndicator = NO;
    table.separatorColor = [UIColor clearColor];
    table.separatorStyle = UITableViewCellSeparatorStyleNone;
    [view addSubview:table];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    //    if ([self.searchResults count] > 0) {
    return [self.searchResults count] + 1;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        NSString *firstCell = @"first";
        DDLoginSuccessCell *first = [[[DDLoginSuccessCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:firstCell] autorelease];
        DDLoginSuccessModel *firstModel = [[DDLoginSuccessModel alloc] init];
        firstModel.IPName = @"手动输入iP地址";
        first.model = firstModel;
        [firstModel release];
        return first;
    } else {
        NSString *second = @"second";
        DDLoginSuccessCell *other = [[[DDLoginSuccessCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:second] autorelease];
        if ([self.searchResults count] > 0) {
            other.model = [self.searchResults objectAtIndex:indexPath.row - 1];
        }
        return other;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    curPos = indexPath.row - 1;
    if (curPos == -1) {
        [self searchFail];
        return;
    }
    DDCloudInfo* cloudInfo = [cloudInfos objectAtIndex:curPos];
    NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
    NSString* pwd = [userDefaults objectForKey:[cloudInfo cloudId]];
    if(pwd != nil){
        [self connect:[cloudInfo adderss] pwdStr:pwd idStr:[cloudInfo cloudId]];
        return;
    }
    
//    [userDefaults release];
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    coverView = [[UIView alloc] initWithFrame:self.view.frame];
    coverView.backgroundColor = [UIColor blackColor];
    coverView.alpha = 0.8;
    [self.view addSubview:coverView];
    [self.view bringSubviewToFront:coverView];
    
    UIWindow *widow = [[[UIApplication sharedApplication] delegate] window];
    alertView = [[UIView alloc] initWithFrame:CGRectMake(self.view.frame.size.width/2.0 - 150, self.view.frame.size.height/2.0 - 100, 300, 200)];
    alertView.alpha = 1;
    //   alertView.backgroundColor = [UIColor blackColor];
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 300, 200)];
    [imageView setImage:[UIImage imageNamed:@"baise.png"]];
    imageView.alpha = 1;
    [alertView addSubview:imageView];
    [imageView release];
    [widow addSubview:alertView];
    [widow bringSubviewToFront:alertView];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 5, 180, 40)];
    titleLabel.textColor = [UIColor blackColor];
    titleLabel.text = @"请输入密码";
    [alertView addSubview:titleLabel];
    [titleLabel release];
    UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(10, 60, 280, 50)];
    [textField setBorderStyle:UITextBorderStyleRoundedRect];
    textField.layer.cornerRadius = 0.2;
    textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    textField.delegate = self;
    textField.tag = 3;
    textField.secureTextEntry = YES;
    textField.returnKeyType = UIReturnKeyDone;
    [alertView addSubview:textField];
    [textField release];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.frame = CGRectMake(10, 140, 50, 50);
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(removeAll:) forControlEvents:UIControlEventTouchUpInside];
    [button setTitle:@"确定" forState:UIControlStateNormal];
    button.tag = OK_BUTTON_TAG;
    [alertView addSubview:button];
    
    button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.frame = CGRectMake(80, 140, 50, 50);
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [button setTitle:@"取消" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(removeAll:) forControlEvents:UIControlEventTouchUpInside];
    [alertView addSubview:button];
    
    UILabel * remeberLabel = [[UILabel alloc] initWithFrame:CGRectMake(150, 150, 120, 30)];
    remeberLabel.textColor = [UIColor blackColor];
    remeberLabel.text = @"记住密码";
    [alertView addSubview:remeberLabel];
    [remeberLabel release];
    
    UIButton *remeberButton = [UIButton buttonWithType:UIButtonTypeCustom];
    remeberButton.tag = REMEBER_TAG;
    remeberButton.frame = CGRectMake(240, 140, 50, 50);
    //    [remeberButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [remeberButton addTarget:self action:@selector(rememberPressed:) forControlEvents:UIControlEventTouchUpInside];
    [remeberButton setImage:[UIImage imageNamed:@"check_false.png"] forState:UIControlStateNormal];
    [alertView addSubview:remeberButton];
}

- (void)rememberPressed:(id)sender {
    UIButton *remeberButton = (UIButton *)sender;
    if (!isRemeber) {
        [remeberButton setImage:[UIImage imageNamed:@"check_true.png"] forState:UIControlStateNormal];
        isRemeber = YES;
    } else {
        [remeberButton setImage:[UIImage imageNamed:@"check_false.png"] forState:UIControlStateNormal];
        isRemeber = NO;
    }
}

- (void)removeAll:(id)sender{
    UIButton* button = sender;
    if (button.tag == OK_BUTTON_TAG) {
        UITextField* pwdField = (UITextField*)[alertView viewWithTag:3];
        NSString* pwd = pwdField.text;
        curPwd = pwd;
        
        if([curPwd isEqualToString:@""] || [curPwd isEqualToString:@"请输入密码"]){
//            pwdField.text = @"请输入密码";
            pwdField.placeholder = @"请输入密码";
            return;
        }
        DDCloudInfo* cloudInfo = [cloudInfos objectAtIndex:curPos];
        
        
        NSString* ip = [cloudInfo adderss];
        NSString* cId = [cloudInfo cloudId];
        curPwd = pwd;
        [self connect:ip pwdStr:pwd idStr:cId];
    }
    
    [coverView removeFromSuperview];
    [alertView removeFromSuperview];
}

#pragma mark - failView

//MARS 显示搜索失败界面
- (void)searchFail {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 250, self.view.frame.size.width, self.view.frame.size.height - 250)];
    view.backgroundColor = [UIColor colorWithString:@"#273826"];
//    view.backgroundColor = [UIColor redColor];
    
    
    //UIControl *cl = [[UIControl alloc] init];
    //cl.frame = self.view.bounds;
    //[cl addTarget:self action:@selector(controlClick) forControlEvents:UIControlEventTouchUpInside];
    //    cl.backgroundColor = [UIColor redColor];
    //[view addSubview:cl];
    
    
    [self.view addSubview:view];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 200, 30)];
    titleLabel.text = @"重新搜索";
    titleLabel.font = [UIFont systemFontOfSize:15];
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.backgroundColor = [UIColor clearColor];
    [view addSubview:titleLabel];
    [titleLabel release];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(10, 50, 100, 30);
    UILabel *buttonLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, button.frame.size.width, button.frame.size.height)];
    buttonLabel.textColor = [UIColor blackColor];
    buttonLabel.font = [UIFont systemFontOfSize:15];
    buttonLabel.backgroundColor = [UIColor whiteColor];
    buttonLabel.textAlignment = NSTextAlignmentCenter;
    buttonLabel.text = @"全局搜索";
    [button addSubview:buttonLabel];
    [button addTarget:self action:@selector(onGlabolSearchPress:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:button];
    
    UILabel *linkLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 80, 200, 30)];
    linkLabel.text = @"连接指定IP";
    linkLabel.font = [UIFont systemFontOfSize:15];
    linkLabel.textColor = [UIColor whiteColor];
    linkLabel.backgroundColor = [UIColor clearColor];
    [view addSubview:linkLabel];
    [linkLabel release];
    
    UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(10, 110, 300, 50)];
    textField.tag = IP_TAG;
    [textField setBorderStyle:UITextBorderStyleRoundedRect];
    textField.layer.cornerRadius = 0.2;
    textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    textField.clearButtonMode = UITextFieldViewModeWhileEditing;
    textField.delegate = self;
    textField.placeholder = @"请输入IP";
    textField.secureTextEntry = NO;
    textField.returnKeyType = UIReturnKeyDone;
    textField.text = @"";
    [view addSubview:textField];
    [textField release];
    
    UITextField *field = [[UITextField alloc] initWithFrame:CGRectMake(10, 190, 300, 50)];
    field.tag = PWD_TAG;
    [field setBorderStyle:UITextBorderStyleRoundedRect];
    field.layer.cornerRadius = 0.2;
    
    field.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    field.clearButtonMode = UITextFieldViewModeWhileEditing;
    field.delegate = self;
    field.placeholder = @"请输入密码";
    field.secureTextEntry = YES;
    field.returnKeyType = UIReturnKeyDone;
    field.text=@"";
    [view addSubview:field];
    [field release];
    
    UIButton *linkButton = [UIButton buttonWithType:UIButtonTypeCustom];
    linkButton.frame = CGRectMake(10, 250, 60, 50);
    
    [linkButton addTarget:self action:@selector(linkButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    UILabel *linkbuttonLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, button.frame.size.width, button.frame.size.height)];
    linkbuttonLabel.textColor = [UIColor blackColor];
    linkbuttonLabel.layer.cornerRadius = 0.2;
    linkbuttonLabel.font = [UIFont systemFontOfSize:15];
    linkbuttonLabel.backgroundColor = [UIColor whiteColor];
    linkbuttonLabel.textAlignment = NSTextAlignmentCenter;
    linkbuttonLabel.text = @"连  接";
    linkButton.tag = CONNECT_BTN_TAG;
    [linkButton addSubview:linkbuttonLabel];
    [view addSubview:linkButton];
    
    
    
}

- (void)setButtonPressed:(id)sender {
    NSLog(@"setbutton------------------------");
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"设置"
                                                   message:@"请输入设备名称"
                                                  delegate:self
                                         cancelButtonTitle:@"取消"
                                         otherButtonTitles:@"确定",nil];
    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
    [alert show];
    [alert release];
}

- (void)connect:(NSString *)ipStr pwdStr:(NSString *)pwdStr idStr:(NSString *)cid{
    self.isSuccess = NO;
    DDVerifyThread* verifyThread = [[DDVerifyThread alloc]init];
    DDCloudInfo* cloudInfo = [[DDCloudInfo alloc]init];
    
    DDTCPListenThread* recvThread = [DDTCPListenThread sharedTCPListener];
    [recvThread setRemeberFlag:isRemeber];
    recvThread.connectCompleteCallback = self;
    
    cloudInfo.adderss = ipStr;
    cloudInfo.cloudId = cid;
    [verifyThread connectToCloud:cloudInfo andPassword:pwdStr];
    verifyThread.connectDelegate =self;
    hub = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:hub];
    hub.delegate = self;
    hub.labelText = @"正在连接服务器";
    [hub show:YES];
    
    NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval:LOGIN_DELAY target:self selector:@selector(connectDelay:) userInfo:nil repeats:NO];
//    [timer fire];
}

- (void)linkButtonPressed:(id)sender {
    
    NSLog(@"press----------------------");
    
    UITextField* ipField = (UITextField *)[self.view viewWithTag:IP_TAG];
    NSString* ipStr = ipField.text;
    
    UITextField* pwdField = (UITextField*)[self.view viewWithTag:PWD_TAG];
    NSString* pwdStr = pwdField.text;
    
    if ([ipStr isEqualToString:@""]) {
        NSLog(@"没有输入ip");
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"错误提示"
                                                       message:@"请输入需要连接的IP地址名称"
                                                      delegate:nil
                                             cancelButtonTitle:@"取消"
                                             otherButtonTitles:@"确定",nil];
        [alert show];
        [alert release];
    }
    
    else if([pwdStr isEqualToString:@""]){
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"错误提示"
                                                       message:@"请输入连接密码"
                                                      delegate:nil
                                             cancelButtonTitle:@"取消"
                                             otherButtonTitles:@"确定",nil];
        [alert show];
        [alert release];
        NSLog(@"没有输入密码");
    }
    else{
        [self connect:ipStr pwdStr:pwdStr idStr:nil];
        NSLog(@"开始连接%@,%@",ipStr,pwdStr);
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
    
    [self createStaticViews];
    
    
    // 这个view在哪
    UIControl *cl = [[UIControl alloc] init];
    cl.frame = self.view.bounds;
    [cl addTarget:self action:@selector(controlClick) forControlEvents:UIControlEventTouchUpInside];
//    cl.backgroundColor = [UIColor redColor];
    [self.view addSubview:cl];
    [self createTableView];
    
//    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
//                                   initWithTarget:self
//                                   action:@selector(dismissKeyboard)];
//    [self.view addGestureRecognizer:tap];
    
    BOOL flag = [DDNetworkUtils IsEnableWIFI];
    if (flag == NO) {
        NSLog(@"WIFI网络连接不可用");
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"错误提示"
                                                       message:@"目前您的设备无法连接WIFI，请打开WIFI开关后继续"
                                                      delegate:nil
                                             cancelButtonTitle:@"取消"
                                             otherButtonTitles:@"确定",nil];
        [alert show];
        [alert release];
    }
    
    //    DDVerifyThread* verifyThread = [[DDVerifyThread alloc]initWithHost:@"172.1.99.159" port:TCP_LISTEN_PORT pwd:@"1"];
    //    [verifyThread connectToCloud];
    //MARS 调用TableView的reload方法，用于重新加载数据
    //[self searchFail];
    [self openUDPServer];
    [self regNotification];
}

- (void)controlClick
{
    // 在这里调用textField对象收起键盘
    [[self.view viewWithTag:IP_TAG]resignFirstResponder];
    [[self.view viewWithTag:PWD_TAG]resignFirstResponder];
}

-(void)dismissKeyboard {
    [imageView1 resignFirstResponder];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)onConnectCompleteOn:(id)info andCode:(int)code{
    [[DDTCPListenThread sharedTCPListener]setConnectCompleteCallback:nil];
    if(code == LOGIN_SUCCESS){
        //登陆成功，调用了回调函数
        NSLog(@"登陆成功，调用了回调函数");
        //判断是否需要保存密码
        if (isRemeber == YES) {
            NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
            DDCloudInfo* cloudInfo = [cloudInfos objectAtIndex:curPos];
            
            [userDefaults setObject:curPwd forKey:[cloudInfo cloudId]];
            [userDefaults synchronize];
//            [userDefaults release];
            curPwd = nil;
            isRemeber = NO;
        }
        //        [hub hide:YES];
        [self jump:nil];
        //       NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval:0.5f target:self selector:@selector(jump:) userInfo:nil repeats:NO];
    }
    else if(code == LOGIN_ERROR_PWD){
        //登陆失败，密码错误
        [DDVerifyThread closeAndClead];
        [DDTCPListenThread closeAndClear];
        [hub hide:YES];
        [hub release];
        hub = [[MBProgressHUD alloc] initWithView:self.view];
        [self.view addSubview:hub];
        hub.mode = MBProgressHUDModeText;
        hub.labelText = @"密码输入错误，请重新输入";
        hub.removeFromSuperViewOnHide = YES;
        NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
        [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];
        [hub showWhileExecuting:@selector(myTask) onTarget:self withObject:nil animated:YES];
    }
    
    isSuccess = YES;
}

-(void)alertView:(UIAlertView*)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if(buttonIndex == 1){
        UITextField* textField = [alertView textFieldAtIndex:0];
        NSString* deviceName = textField.text;
        NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setObject:deviceName forKey:@"CLOUD_NAME"];
        [userDefaults synchronize];
//        [userDefaults release];
        
    }
}

#pragma udp callback
//UDP收到消息时调用的回调函数
-(void)udpSocket:(GCDAsyncUdpSocket *)sock didReceiveData:(NSData *)data fromAddress:(NSData *)address withFilterContext:(id)filterContext{
    NSString* localIp = [self getIPAddress];
    NSString* remoteIp = [address host];
    if(![localIp isEqualToString:remoteIp]){
        //说明消息不是来自于我自己的机器，
        DDSearchAllACK* allAck = [[DDSearchAllACK alloc]initWithData:data];
        NSString* cloudId = [allAck getCloudId];
        NSString* cloudName = [allAck getCloudName];
        DDCloudInfo* cloudInfo = [[DDCloudInfo alloc]init];
        [cloudInfo setCloudId:cloudId];
        [cloudInfo setCloudName:cloudName];
        [cloudInfo setAdderss:remoteIp];
        if (![cloudInfos containsObject:cloudInfo]) {
            [cloudInfos addObject:cloudInfo];
            DDLoginSuccessModel* model = [[DDLoginSuccessModel alloc]init];
            [model setIPAddress:remoteIp];
            [model setIPName:cloudName];
            [[self searchResults]addObject:model];
            hasSearchResult = YES;
            [table reloadData];
        }
    }
    [_udpSocket receiveOnce:nil];
}
- (void)myTask {
	sleep(2);
}

-(void)searchImagePressed:(id)sender{
    [self openUDPServer];
    [self createTableView];
}

-(void)blink{
    [UIView animateWithDuration:0.1
                          delay:0
                        options:UIViewAnimationOptionCurveEaseOut animations:^(void){
                            imageView1.alpha = 0.0;
                        }completion:^(BOOL finished){
                            [UIView animateWithDuration:0.5
                                                  delay:0.0
                                                options:UIViewAnimationOptionAutoreverse | UIViewAnimationOptionRepeat
                                             animations:^(void){
                                                 [UIView setAnimationRepeatCount:10];
                                                 imageView1.alpha = 1.0;
                                             }completion:^(BOOL finished){
                                                 NSLog(@"动画执行完毕");
                                                 //需要停止掉组播消息的监听
                                                 [_udpSocket close];
                                                 if(hasSearchResult){
                                                     searchLabel.text = @"搜索结束";
                                                 }
                                                 else{
                                                     searchLabel.text = @"搜索失败";
                                                     [self searchFail];
                                                 }
                                             }];
                            
                        }];
}

-(void)onGlabolSearchPress:(id)sender{
    //重新显示
    [self createTableView];
    //开始搜索
    [self openUDPServer];
}

//获得当前设备主机名称
+ (NSString *)hostname
{
    char baseHostName[256];
    int success = gethostname(baseHostName, 255);
    if (success != 0) return nil;
    baseHostName[255] = '\0';
    
#if !TARGET_IPHONE_SIMULATOR
    return [NSString stringWithFormat:@"%s.local", baseHostName];
#else
    return [NSString stringWithFormat:@"%s", baseHostName];
#endif
}
//获得本地ip地址
+ (NSString *)localIPAddress
{
    struct hostent *host = gethostbyname([[self hostname] UTF8String]);
    if (!host) {herror("resolv"); return nil;}
    struct in_addr **list = (struct in_addr **)host->h_addr_list;
    return [NSString stringWithCString:inet_ntoa(*list[0]) encoding:NSUTF8StringEncoding];
}

- (NSString *)getIPAddress {
    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);
    if (success == 0) {
        // Loop through linked list of interfaces
        temp_addr = interfaces;
        while(temp_addr != NULL) {
            if(temp_addr->ifa_addr->sa_family == AF_INET) {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }
            temp_addr = temp_addr->ifa_next;
        }
    }
    // Free memory
    freeifaddrs(interfaces);
    return address;
    
}
-(void)jump:(NSTimer*)timer{
    DDSuccessViewController* successViewController = [[DDSuccessViewController alloc]init];
    //[self presentViewController:successViewController animated:NO completion:nil];
    ((DDAppDelegate*)[UIApplication sharedApplication].delegate).window.rootViewController = successViewController;
    [successViewController release];
}

#pragma UIResponder

-(BOOL)textFieldShouldReturn:(UITextField*)textField{
    int curTag = textField.tag;
    curTag = curTag + 1;
    if(curTag == CONNECT_BTN_TAG){
        [textField resignFirstResponder];
        [self linkButtonPressed:nil];
        return NO;
    }
    UIResponder* nextRe = [textField.superview viewWithTag:curTag];
    
    if(nextRe){
        [nextRe becomeFirstResponder];
    }
    else{
        [textField resignFirstResponder];
    }
    return NO;
}

#pragma Timer
-(void)connectDelay:(NSTimer*)theTimer{
    NSLog(@"timer--------------------");
    if(isSuccess == YES){
        return;
    }
    
    [DDVerifyThread closeAndClead];
    [DDTCPListenThread closeAndClear];
    [hub hide:YES];
    [hub release];
    hub = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:hub];
    hub.mode = MBProgressHUDModeText;
    hub.labelText = @"连接失败，请重新输入IP地址";
    hub.removeFromSuperViewOnHide = YES;
    [hub show:YES];
    
    [hub hide:YES afterDelay:3];

}

#pragma server closed
- (void)serverClosed{
    hub = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:hub];
    hub.mode = MBProgressHUDModeText;
    hub.labelText = @"服务器端已经关闭，请重新选择服务器";
    hub.removeFromSuperViewOnHide = YES;
    [hub show:YES];
    
    [hub hide:YES afterDelay:3];
}
//
//- (BOOL)textFieldShouldReturn:(UITextField *)textField
//{
//    [textField resignFirstResponder];
//    return YES;
//}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    NSLog(@"touchesBegan---------------------");
    [[self.view viewWithTag:IP_TAG]resignFirstResponder];
    [[self.view viewWithTag:PWD_TAG]resignFirstResponder];
}


- (void)regNotification
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

- (void)unregNotification
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];
}


- (void)keyboardWillChangeFrame:(NSNotification *)notification
{
    NSDictionary *info = [notification userInfo];
    CGFloat duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    CGRect beginKeyboardRect = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];
    CGRect endKeyboardRect = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    CGFloat yOffset = endKeyboardRect.origin.y - beginKeyboardRect.origin.y;
    
    CGRect inputFieldRect = [self.view viewWithTag:IP_TAG].frame;
    CGRect moreBtnRect = self.view.frame;
    
    inputFieldRect.origin.y += yOffset;
    moreBtnRect.origin.y += yOffset;
    
    [UIView animateWithDuration:duration animations:^{
        //[self.view viewWithTag:IP_TAG].frame = inputFieldRect;
        //[self.view viewWithTag:PWD_TAG].frame = moreBtnRect;
        self.view.frame = moreBtnRect;
    }];
}

@end
